package main

import (
	"flag"
	"github.com/sirupsen/logrus"
	"gitlab.yctc.tech/zhiting/disk-manager.git/internal/config"
	app "gitlab.yctc.tech/zhiting/disk-manager.git/internal/grpc"
	"gitlab.yctc.tech/zhiting/disk-manager.git/pkg/lvm"
	"gitlab.yctc.tech/zhiting/disk-manager.git/pkg/proto"
	"google.golang.org/grpc"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var configFile = flag.String("c", "app.yaml", "config file")

func main() {
	flag.Parse()
	opts := config.InitConfig(*configFile)
	logrus.SetLevel(logrus.DebugLevel)
	//logrus.SetReportCaller(true)

	logrus.Info("starting disk manager gRPC server")
	if err := lvm.DetectEnv(); err != nil {
		log.Fatalf("lvm env err %v", err)
	}
	diskManagerServer := app.NewDiskManagerServer(opts)
	if err := diskManagerServer.InitEnv(); err != nil {
		log.Fatalf("disk-manager env err %v", err)
	}
	lis, err := net.Listen("tcp", ":9090")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	grpcServer := grpc.NewServer()
	proto.RegisterDiskManagerServer(grpcServer, diskManagerServer)

	result := make(chan struct{}, 1)
	go func() {
		err = grpcServer.Serve(lis)
		if err != nil {
			logrus.Error(err)
			result <- struct{}{}
			return
		}
	}()
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	select {
	case <-sig:
		// Exit by user
		grpcServer.Stop()
		time.Sleep(100 * time.Microsecond)
	case <-result:
	}
	logrus.Info("shutting down.")
}
